import requests
from .utils import load_api_info
import json

def generate_response(messages, service):
    api_key, api_url, model = load_api_info(service)
    if not api_key or not api_url or not model:
        print(f"未找到 {service} 的有效 API 信息或模型配置。")
        return None

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "model": model,
        "messages": messages,
        "stream": True  # 开启流式输出
    }

    try:
        response = requests.post(api_url, headers=headers, json=data, stream=True)
        response.raise_for_status()

        partial_text = ""
        for line in response.iter_lines():
            if line:
                # 去掉 "data: " 前缀
                line = line.lstrip(b'data: ')
                try:
                    chunk = json.loads(line)
                    if 'choices' in chunk and len(chunk['choices']) > 0:
                        delta = chunk['choices'][0].get('delta', {})
                        content = delta.get('content')
                        if content:
                            partial_text += content
                            yield content
                except json.JSONDecodeError:
                    continue

    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except (KeyError, IndexError):
        print("解析响应结果出错。")